package com.simpilemvc.web.utils;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.simpilemvc.web.context.ActionModel;
import com.simpilemvc.web.context.HandlerMapping;

/**
 * @author yangwenkui
 * @version v2.0
 * @time 2016年10月28日 下午10:07:28
 */
public class ConfigParse {

	@SuppressWarnings("unchecked")
	public static void parse(File file) throws DocumentException{
		SAXReader reader = new SAXReader();
		Document document = reader.read(file);
		Element root = document.getRootElement();
		Element actions = root.element("actions");
		List<Element> actionList = actions.elements();
		for (Element element : actionList) {
			String path = element.attributeValue("path");
			String type = element.attributeValue("type");
			String method = element.attributeValue("method");
			ActionModel actionModel = new ActionModel();
			actionModel.setType(type);
			actionModel.setMethod(method);
			List<Element> results = element.elements("result");
			if(results == null){
				continue;
			}
			Map<String, String> resultMap = new HashMap<String, String>();
			for (Element result : results) {
				String name = result.attributeValue("name");
				String value = result.attributeValue("value");
				resultMap.put(name, value);
			}
			actionModel.setResults(resultMap);
			HandlerMapping.addMapping(path, actionModel);
		}
	}
	
}
